package com.nutrition.health.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nutrition.health.model.UserHealthProfile;
import com.nutrition.health.service.DeepSeekAIService;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.Period;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service
public class DeepSeekAIServiceImpl implements DeepSeekAIService {

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekAIServiceImpl.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final ExecutorService executorService = Executors.newCachedThreadPool();

     @Value("${app.deepseek.api-key}")
     private String apiKey;

     @Value("${app.deepseek.local.api-url}")
     private String localApiUrl;

    @Value("${app.deepseek.api-url}")
    private String apiUrl;

    // 根据用户提供的curl示例修改默认URL
    @Value("${app.local-model.api-url:http://localhost:3000/api/chat}")
    private String localModelApiUrl = "http://localhost:3000/api/chat";

    private String promptTemplate;
    private String nutritionPromptTemplate;

    public DeepSeekAIServiceImpl() {
        try {
            // 从资源文件中加载提示词模板
            ClassPathResource resource = new ClassPathResource("deepseekPrompt.txt");
            promptTemplate = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);

            // 设置营养计算的提示词模板
            nutritionPromptTemplate = "你是一个精通营养学的专家，用户会把他食用的食品和大概的克数给你，你需要通过知识库进行计算，计算出这些食品的卡路里 蛋白质 碳水 脂肪克数，并且返回这些信息，格式以 JSON 形式返回，必须包含以下字段：food(食品名称)、weight(克数)、calories(卡路里)、protein(蛋白质克数)、carbohydrates(碳水克数)、fat(脂肪克数)。不需要返回除 JSON 外的任何信息，这会影响到后续程序处理。";
        } catch (IOException e) {
            logger.error("Failed to load DeepSeek prompt template", e);
            promptTemplate = "你是一个精通营养学和医术精湛的医生，拥有丰富的基础病诊断经验，能根据每个人的情况给出具体的健康建议，健康建议包括：日常饮食注意事项、运动频率和项目、其它注意事项如睡眠、起居等，每次建议在 300-500 字左右。";
            nutritionPromptTemplate = "你是一个精通营养学的专家，用户会把他食用的食品和大概的克数给你，你需要通过知识库进行计算，计算出这些食品的卡路里 蛋白质 碳水 脂肪克数，并且返回这些信息，格式以 JSON 形式返回，必须包含以下字段：food(食品名称)、weight(克数)、calories(卡路里)、protein(蛋白质克数)、carbohydrates(碳水克数)、fat(脂肪克数)。不需要返回除 JSON 外的任何信息，这会影响到后续程序处理。";
        }
    }

    @Override
    public void generateHealthAdvice(UserHealthProfile profile, SseEmitter emitter) {
        executorService.execute(() -> {
            try {
                // 构建用户健康信息
                String userHealthInfo = buildUserHealthInfo(profile);

                // 构建完整提示词
                String fullPrompt = promptTemplate + "\n\n用户健康信息：\n" + userHealthInfo;

                // 调用DeepSeek API
                callDeepSeekAPI(fullPrompt, emitter);

                // 完成SSE流
                emitter.complete();
            } catch (Exception e) {
                logger.error("Failed to generate health advice", e);
                try {
                    emitter.send(SseEmitter.event().name("error").data("生成健康建议失败: " + e.getMessage()));
                    emitter.complete();
                } catch (IOException ex) {
                    logger.error("Failed to send error event", ex);
                    emitter.completeWithError(ex);
                }
            }
        });
    }

    @Override
    public void generateFoodHealthAdvice(UserHealthProfile profile, Map<String, Object> foodAnalysisResult, String customPrompt, SseEmitter emitter) {
        executorService.execute(() -> {
            try {
                // 构建用户健康信息
                String userHealthInfo = buildUserHealthInfo(profile);
                // 构建食品分析结果信息
                String foodInfo;

                // 尝试从foodAnalysisResult中获取foodInfo字段
                if (foodAnalysisResult.containsKey("foodData[foodInfo]")) {
                    foodInfo = foodAnalysisResult.get("foodData[foodInfo]").toString();
                    logger.info("使用前端传递的foodInfo: {}", foodInfo);
                } else {
                    // 如果没有foodInfo字段，则使用buildFoodAnalysisInfo方法构建
                    foodInfo = buildFoodAnalysisInfo(foodAnalysisResult);
                    logger.info("使用后端构建的foodInfo: {}", foodInfo);
                }

                // 确定使用的提示词模板
                String basePrompt;
                if (customPrompt != null && !customPrompt.isEmpty()) {
                    basePrompt = customPrompt;
                } else {
                    basePrompt = "你是一个精通营养学、医术高明的专家，我会给你一个病人的基础信息，以及一个食品的分析结果，给我输出适合这个病人的食用建议，需要符合病人的身体情况，如果不建议食用也说出具体的理由，总共 300 字左右。";
                }

                // 构建完整提示词
                String fullPrompt = basePrompt + "\n\n用户健康信息：\n" + userHealthInfo + "\n\n食品分析结果：\n" + foodInfo;

                logger.info("生成食品健康建议的完整提示词: {}", fullPrompt);

                // 调用DeepSeek API
                callDeepSeekAPI(fullPrompt, emitter);

                // 完成SSE流
                emitter.complete();
            } catch (Exception e) {
                logger.error("Failed to generate food health advice", e);
                try {
                    emitter.send(SseEmitter.event().name("error").data("生成食品健康建议失败: " + e.getMessage()));
                    emitter.complete();
                } catch (IOException ex) {
                    logger.error("Failed to send error event", ex);
                    emitter.completeWithError(ex);
                }
            }
        });
    }

    /**
     * 生成健康建议（使用本地模型，非流式返回）
     * @param profile 用户健康档案
     * @return 健康建议文本
     */
    @Override
    public String generateHealthAdviceWithLocalModel(UserHealthProfile profile) {
        try {
            // 构建用户健康信息
            String userHealthInfo = buildUserHealthInfo(profile);

            // 构建完整提示词
            String fullPrompt = promptTemplate + "\n\n用户健康信息：\n" + userHealthInfo;

            // 调用本地模型API
            String response = callLocalModelAPI(fullPrompt);

            logger.info("本地模型生成的健康建议: {}", response);

            return response;
        } catch (Exception e) {
            logger.error("使用本地模型生成健康建议失败", e);
            return "生成健康建议失败: " + e.getMessage();
        }
    }

    /**
     * 生成食品健康建议（使用本地模型，非流式返回）
     * @param profile 用户健康档案
     * @param foodAnalysisResult 食品分析结果
     * @param customPrompt 自定义提示词
     * @return 食品健康建议文本
     */
    @Override
    public String generateFoodHealthAdviceWithLocalModel(UserHealthProfile profile, Map<String, Object> foodAnalysisResult, String customPrompt) {
        try {
            // 构建用户健康信息
            String userHealthInfo = buildUserHealthInfo(profile);

            // 构建食品分析结果信息
            String foodInfo;

            // 尝试从foodAnalysisResult中获取foodInfo字段
            if (foodAnalysisResult.containsKey("foodData[foodInfo]")) {
                foodInfo = foodAnalysisResult.get("foodData[foodInfo]").toString();
                logger.info("使用前端传递的foodInfo: {}", foodInfo);
            } else {
                // 如果没有foodInfo字段，则使用buildFoodAnalysisInfo方法构建
                foodInfo = buildFoodAnalysisInfo(foodAnalysisResult);
                logger.info("使用后端构建的foodInfo: {}", foodInfo);
            }

            // 确定使用的提示词模板
            String basePrompt;
            if (customPrompt != null && !customPrompt.isEmpty()) {
                basePrompt = customPrompt;
            } else {
                basePrompt = "你是一个精通营养学、医术高明的专家，我会给你一个病人的基础信息，以及一个食品的分析结果，给我输出适合这个病人的食用建议，需要符合病人的身体情况，如果不建议食用也说出具体的理由，总共 300 字左右。";
            }

            // 构建完整提示词
            String fullPrompt = basePrompt + "\n\n用户健康信息：\n" + userHealthInfo + "\n\n食品分析结果：\n" + foodInfo;

            logger.info("生成食品健康建议的完整提示词: {}", fullPrompt);

            // 调用本地模型API
            String response = callLocalModelAPI(fullPrompt);

            logger.info("本地模型生成的食品健康建议: {}", response);

            return response;
        } catch (Exception e) {
            logger.error("使用本地模型生成食品健康建议失败", e);
            return "生成食品健康建议失败: " + e.getMessage();
        }
    }

    @Override
    public Map<String, Double> calculateNutrition(String foodName, Double amount) {
        try {
            logger.info("开始计算食品营养成分: {}, 数量: {}克", foodName, amount);

            // 构建提示词
            String prompt = String.format("%s\n\n食品名称：%s\n克数：%.1f克",
                nutritionPromptTemplate, foodName, amount);

            logger.info("调用DeepSeek API计算营养成分，提示词: {}", prompt);

            // 调用DeepSeek API获取营养信息
            String response = callDeepSeekAPIForNutrition(prompt);

            logger.info("DeepSeek API返回结果: {}", response);

            // 解析JSON响应
            Map<String, Double> nutritionInfo = parseNutritionResponse(response);

            // 如果解析失败，返回默认值
            if (nutritionInfo.isEmpty()) {
                nutritionInfo.put("calories", 0.0);
                nutritionInfo.put("protein", 0.0);
                nutritionInfo.put("carbohydrates", 0.0);
                nutritionInfo.put("fat", 0.0);
            }

            return nutritionInfo;
        } catch (Exception e) {
            logger.error("Failed to calculate nutrition for food: {}, amount: {}", foodName, amount, e);
            // 返回默认值
            Map<String, Double> defaultValues = new HashMap<>();
            defaultValues.put("calories", 0.0);
            defaultValues.put("protein", 0.0);
            defaultValues.put("carbohydrates", 0.0);
            defaultValues.put("fat", 0.0);
            return defaultValues;
        }
    }

    /**
     * 解析营养计算的响应
     * @param response API响应
     * @return 营养信息映射
     */
    private Map<String, Double> parseNutritionResponse(String response) {
        Map<String, Double> nutritionInfo = new HashMap<>();

        try {
            logger.info("开始解析营养成分响应: {}", response);

            // 预处理响应字符串，去除可能的```json和```标记
            String cleanedResponse = response;
            if (response.contains("```json")) {
                cleanedResponse = response.substring(response.indexOf("```json") + 7);
                if (cleanedResponse.contains("```")) {
                    cleanedResponse = cleanedResponse.substring(0, cleanedResponse.indexOf("```"));
                }
            } else if (response.contains("```")) {
                cleanedResponse = response.substring(response.indexOf("```") + 3);
                if (cleanedResponse.contains("```")) {
                    cleanedResponse = cleanedResponse.substring(0, cleanedResponse.indexOf("```"));
                }
            }

            logger.info("清理后的JSON字符串: {}", cleanedResponse);

            // 尝试解析JSON响应
            JsonNode jsonNode = objectMapper.readTree(cleanedResponse);

            // 处理DS返回的特定格式
            // {
            //   "food": "巧克力",
            //   "weight": 10.0,
            //   "calories": 54.6,
            //   "protein": 0.7,
            //   "carbohydrates": 5.7,
            //   "fat": 3.3
            // }

            // 提取营养信息
            if (jsonNode.has("calories")) {
                double calories = jsonNode.get("calories").asDouble();
                nutritionInfo.put("calories", calories);
                logger.info("解析到卡路里: {}", calories);
            }

            if (jsonNode.has("protein")) {
                double protein = jsonNode.get("protein").asDouble();
                nutritionInfo.put("protein", protein);
                logger.info("解析到蛋白质: {}g", protein);
            }

            if (jsonNode.has("carbohydrates") || jsonNode.has("碳水")) {
                Double carbs = jsonNode.has("carbohydrates") ?
                    jsonNode.get("carbohydrates").asDouble() :
                    jsonNode.get("碳水").asDouble();
                nutritionInfo.put("carbohydrates", carbs);
                logger.info("解析到碳水化合物: {}g", carbs);
            }

            if (jsonNode.has("fat") || jsonNode.has("脂肪")) {
                Double fat = jsonNode.has("fat") ?
                    jsonNode.get("fat").asDouble() :
                    jsonNode.get("脂肪").asDouble();
                nutritionInfo.put("fat", fat);
                logger.info("解析到脂肪: {}g", fat);
            }

            // 如果有weight字段，记录下来
            if (jsonNode.has("weight")) {
                double weight = jsonNode.get("weight").asDouble();
                nutritionInfo.put("weight", weight);
                logger.info("解析到重量: {}g", weight);
            }

            logger.info("营养成分解析完成: {}", nutritionInfo);

        } catch (Exception e) {
            logger.error("解析营养成分响应失败: {}", response, e);
            logger.error("异常详情: ", e);
            logger.info("返回默认营养值");
        }

        return nutritionInfo;
    }

    /**
     * 调用DeepSeek API获取营养信息
     * @param prompt 提示词
     * @return API响应
     * @throws IOException 如果API调用失败
     * "http://localhost:11434/api/generate"
     */
    private String callDeepSeekAPIForNutrition(String prompt) throws IOException {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);

        // 构建请求体
        ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", "deepseek-chat");
        requestBody.put("stream", false);

        ArrayNode messages = objectMapper.createArrayNode();
        ObjectNode userMessage = objectMapper.createObjectNode();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);
        messages.add(userMessage);

        requestBody.set("messages", messages);

        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        // 处理响应
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            System.out.println("responseCode: " + connection.getResponseCode());
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = br.readLine()) != null) {
                    response.append(line);
                }

                // 解析响应
                JsonNode jsonResponse = objectMapper.readTree(response.toString());
                if (jsonResponse.has("choices") && jsonResponse.get("choices").isArray() && jsonResponse.get("choices").size() > 0) {
                    JsonNode choice = jsonResponse.get("choices").get(0);
                    if (choice.has("message") && choice.get("message").has("content")) {
                        String content = choice.get("message").get("content").asText();
                        return content;
                    }
                }

                return response.toString();
            }
        } else {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    errorResponse.append(line);
                }
                logger.error("DeepSeek API error: {}", errorResponse);
                throw new IOException("DeepSeek API error: " + errorResponse);
            }
        }
    }

    /**
     * 构建用户健康信息
     * @param profile 用户健康档案
     * @return 用户健康信息文本
     */
    private String buildUserHealthInfo(UserHealthProfile profile) {
        StringBuilder info = new StringBuilder();

        // 计算年龄
        int age = 0;
        if (profile.getDateOfBirth() != null) {
            age = Period.between(profile.getDateOfBirth(), LocalDate.now()).getYears();
        }

        info.append("年龄: ").append(age).append("岁\n");
        info.append("性别: ").append(profile.getGender() == UserHealthProfile.Gender.MALE ? "男" :
                                    profile.getGender() == UserHealthProfile.Gender.FEMALE ? "女" : "其他").append("\n");
        info.append("身高: ").append(profile.getHeight()).append("厘米\n");
        info.append("体重: ").append(profile.getWeight()).append("公斤\n");

        if (profile.getTargetWeight() != null) {
            info.append("目标体重: ").append(profile.getTargetWeight()).append("公斤\n");
        }

        if (profile.getActivityLevel() != null) {
            info.append("活动水平: ");
            switch (profile.getActivityLevel()) {
                case SEDENTARY:
                    info.append("久坐不动（几乎不运动）");
                    break;
                case LIGHTLY_ACTIVE:
                    info.append("轻度活动（每周运动1-3次）");
                    break;
                case MODERATELY_ACTIVE:
                    info.append("中度活动（每周运动3-5次）");
                    break;
                case VERY_ACTIVE:
                    info.append("高度活动（每周运动6-7次）");
                    break;
                case EXTREMELY_ACTIVE:
                    info.append("极度活动（每天高强度运动或体力劳动）");
                    break;
            }
            info.append("\n");
        }

        if (profile.getGoal() != null) {
            info.append("健康目标: ");
            switch (profile.getGoal()) {
                case LOSE_WEIGHT:
                    info.append("减肥");
                    break;
                case MAINTAIN_WEIGHT:
                    info.append("保持体重");
                    break;
                case GAIN_WEIGHT:
                    info.append("增重");
                    break;
                case BUILD_MUSCLE:
                    info.append("增肌");
                    break;
                case IMPROVE_HEALTH:
                    info.append("改善健康");
                    break;
            }
            info.append("\n");
        }

        if (profile.getHealthConditions() != null && !profile.getHealthConditions().isEmpty()) {
            info.append("健康状况: ").append(profile.getHealthConditions()).append("\n");
        }

        if (profile.getDietaryRestrictions() != null && !profile.getDietaryRestrictions().isEmpty()) {
            info.append("饮食限制: ").append(profile.getDietaryRestrictions()).append("\n");
        }

        return info.toString();
    }

    /**
     * 构建食品分析结果信息
     * @param foodAnalysisResult 食品分析结果
     * @return 食品分析结果文本
     */
    private String buildFoodAnalysisInfo(Map<String, Object> foodAnalysisResult) {
        StringBuilder info = new StringBuilder();

        if (foodAnalysisResult != null) {
            // 添加食品基本信息
            info.append("食品名称: ").append(foodAnalysisResult.getOrDefault("name", "未知食品")).append("\n");
            info.append("食品类别: ").append(foodAnalysisResult.getOrDefault("category", "未分类")).append("\n");

            // 添加营养成分信息
            info.append("热量: ").append(foodAnalysisResult.getOrDefault("calories", 0)).append(" kcal/100g\n");
            info.append("蛋白质: ").append(foodAnalysisResult.getOrDefault("protein", 0)).append(" g/100g\n");
            info.append("脂肪: ").append(foodAnalysisResult.getOrDefault("fat", 0)).append(" g/100g\n");
            info.append("碳水化合物: ").append(foodAnalysisResult.getOrDefault("carbs", 0)).append(" g/100g\n");
            info.append("膳食纤维: ").append(foodAnalysisResult.getOrDefault("fiber", 0)).append(" g/100g\n");

            // 添加描述信息（如果有）
            if (foodAnalysisResult.containsKey("description") && foodAnalysisResult.get("description") != null) {
                info.append("描述: ").append(foodAnalysisResult.get("description")).append("\n");
            }
        } else {
            info.append("未提供食品分析结果");
        }

        return info.toString();
    }

    /**
     * 调用DeepSeek API
     * @param prompt 提示词
     * @param emitter SSE发射器
     * @throws IOException 如果API调用失败
     * "http://localhost:11434/api/generate"
     */
    private void callDeepSeekAPI(String prompt, SseEmitter emitter) throws IOException {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
         connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);
        connection.setChunkedStreamingMode(0);

        // 构建请求体
        ObjectNode requestBody = objectMapper.createObjectNode();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("stream", true);

        ArrayNode messages = objectMapper.createArrayNode();
        ObjectNode userMessage = objectMapper.createObjectNode();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);
        messages.add(userMessage);

        requestBody.set("messages", messages);
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 处理响应
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                StringBuilder responseContent = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("data: ")) {
                        String data = line.substring(6);

                        // 跳过 [DONE] 消息
                        if ("[DONE]".equals(data)) {
                            continue;
                        }

                        try {
                            JsonNode jsonResponse = objectMapper.readTree(data);
                            if (jsonResponse.has("choices") && jsonResponse.get("choices").isArray() && jsonResponse.get("choices").size() > 0) {
                                JsonNode choice = jsonResponse.get("choices").get(0);
                                if (choice.has("delta") && choice.get("delta").has("content")) {
                                    String content = choice.get("delta").get("content").asText();
                                    if (!content.isEmpty()) {
                                        // 发送内容片段
                                        emitter.send(SseEmitter.event().name("message").data(content));
                                        responseContent.append(content);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            logger.warn("Failed to parse SSE message: {}", data, e);
                        }
                    }
                }

                logger.info("Generated health advice: {}", responseContent);
            }
        } else {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    errorResponse.append(line);
                }
                logger.error("DeepSeek API error: {}", errorResponse);
                throw new IOException("DeepSeek API error: " + errorResponse);
            }
        }
    }

    /**
     * 调用本地模型API
     * @param prompt 提示词
     * @return API响应
     * @throws IOException 如果API调用失败
     */
    private String callLocalModelAPI(String prompt) throws IOException {
        URL url = new URL(localModelApiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setConnectTimeout(600000); // 60秒连接超时
        connection.setReadTimeout(600000);    // 60秒读取超时

        // 构建请求体 - 根据用户提供的curl示例，本地模型只需要prompt参数
        ObjectNode requestBody = objectMapper.createObjectNode();
        requestBody.put("prompt", prompt);

        logger.info("调用本地模型API，URL: {}, 提示词: {}", localModelApiUrl, prompt);

        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 处理响应
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = br.readLine()) != null) {
                    response.append(line);
                }

                String rawResponse = response.toString();
                
                // 清理响应文本
                String cleanedResponse = rawResponse;
                
                // 1. 移除JSON响应格式
                if (cleanedResponse.startsWith("{\"response\":\"")) {
                    cleanedResponse = cleanedResponse.substring("{\"response\":\"".length());
                    if (cleanedResponse.endsWith("\"}")) {
                        cleanedResponse = cleanedResponse.substring(0, cleanedResponse.length() - 2);
                    }
                }
                
                // 2. 替换转义的换行符为实际换行符
                cleanedResponse = cleanedResponse.replace("\\n", "\n");
                
                // 3. 移除多余的###标记
                cleanedResponse = cleanedResponse.replaceAll("###\\s*\\d+\\.?\\s*", "");
                
                // 4. 移除其他特殊字符
                cleanedResponse = cleanedResponse.replace("\\", "");
                
                // 5. 清理多余的空行
                cleanedResponse = cleanedResponse.replaceAll("\\n{3,}", "\n\n");
                
                // 6. 替换英文词汇为中文（英文）格式
                cleanedResponse = cleanedResponse
                    // 食物和营养相关
                    .replace("his calorie burn", "他的卡路里消耗（calorie burn）")
                    .replace("Bodyweight Training", "体重训练（Bodyweight Training）")
                    .replace("calorie", "卡路里（calorie）")
                    .replace("protein", "蛋白质（protein）")
                    .replace("carbohydrates", "碳水化合物（carbohydrates）")
                    .replace("fat", "脂肪（fat）")
                    .replace("fiber", "膳食纤维（fiber）")
                    .replace("gluten", "麸质（gluten）")
                    .replace("Halal", "清真（Halal）")
                    .replace("GI", "血糖指数（GI）")
                    .replace("him", "他");
                
                return cleanedResponse.trim();
            }
        } else {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    errorResponse.append(line);
                }
                logger.error("本地模型API错误: {}", errorResponse);
                throw new IOException("本地模型API错误: " + errorResponse);
            }
        }
    }
}

